﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NPOI.HSSF.Record;
using NPOI.HSSF.UserModel;
using NPOI.OpenXmlFormats.Dml;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.SS.Util;

/**
 * TODO 添加将Excel转换成制表符文本文档
 * 将文本文档添加进数据库
 * 使用MySql语句：
 * LOAD DATA INFILE 'filename.txt' INTO TABLE tablename
 * CHARACTER SET gb_2312
 * IGNORE 1 LINES
 * FIELDS TERMINATED BY ',' ENCLOSED BY '"'
 * LINES TERMINATED BY '\r\n'
 * */
using System.Threading;


namespace timetable
{
    class DataIO
    {
        public readonly int CourseNumADay = 8;
		public Dictionary<string,List<int>> teacherTakeCourseTime ;
        //public List<Dictionary<string, string>> RawData;
        public List<Student> Students;
        public List<List<List<string>>> AllTeacherList;
        public List<string[]> courseAmount = new List<string[]>(); // 获取教学班和人数表
        

        private static readonly string[] Coursename =
        {
            "语文", "数学", "英语", "物理", "化学", "生物", "政治", "历史", "地理", "通技"
        };

        public static string[] TypeName = 
        {
            "物理_化学_生物", "物理_化学_政治", "物理_化学_历史", "物理_化学_地理", "物理_化学_通技",
            "物理_生物_政治", "物理_生物_历史", "物理_生物_地理", "物理_生物_通技", "物理_政治_历史",
            "物理_政治_地理", "物理_政治_通技", "物理_历史_地理", "物理_历史_通技", "物理_地理_通技",
            "化学_生物_政治", "化学_生物_历史", "化学_生物_地理", "化学_生物_通技", "化学_政治_历史",
            "化学_政治_地理", "化学_政治_通技", "化学_历史_地理", "化学_历史_通技", "化学_地理_通技",
            "生物_政治_历史", "生物_政治_地理", "生物_政治_通技", "生物_历史_地理", "生物_历史_通技",
            "生物_地理_通技", "政治_历史_地理", "政治_历史_通技", "政治_地理_通技", "历史_地理_通技"
        };

        private static readonly string[] DayName =
        {
            "周一", "周二", "周三", "周四", "周五",
        };

        public DataIO()
        {
            Students = new List<Student>();
            //RawData = new List<Dictionary<string, string>>();
        }

        public void GetData(string filePath)
        {

            char[] charArray = {','};
            List<Dictionary<string,string>> data = 
                new List<Dictionary<string, string>>();
            List<string> columns = new List<string>();
            try
            {
                FileStream aFile = new FileStream(filePath, FileMode.Open);
                StreamReader sr = new StreamReader(aFile);

                String line = sr.ReadLine();
                String[] stringArray = line.Split(charArray);

                for (int x = 0; x < stringArray.GetUpperBound(0); x++)
                {
                    columns.Add(stringArray[x]);
                }

                line = sr.ReadLine();
                while (line != null)
                {
                    stringArray = line.Split(charArray);
                    Dictionary<string,string> dataRow = new Dictionary<string, string>();
                    Student student= new Student();
                    for (int x = 0; x < stringArray.GetUpperBound(0); x++)
                    {
                        dataRow.Add(columns[x], stringArray[x]);
                    }

                    student.Id = stringArray[0];
                    student.Name = stringArray[1];
                    student.Sex = stringArray[2];
                    student.Chinese = stringArray[3];
                    student.Math = stringArray[4];
                    student.English = stringArray[5];
                    student.Physics = stringArray[6];
                    student.Chemistry = stringArray[7];
                    student.Biology = stringArray[8];
                    student.Politics = stringArray[9];
                    student.History = stringArray[10];
                    student.Geography = stringArray[11];
                    student.Computer = stringArray[12];

                    Students.Add(student);
                    data.Add(dataRow);

                    line = sr.ReadLine();
                }

                sr.Close();
                //RawData = data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("An IO exception has been thrown!");
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
                //RawData = data;
            }
        }

        

        public List<Student> GetStuInfoFromExcel(string filePath)
        {
            try
            {
                using (FileStream fs = new FileStream(filePath,FileMode.Open))
                {
                    IWorkbook book = new HSSFWorkbook(fs);
                    ISheet sheet = book.GetSheetAt(0);
                    int rFirst = sheet.FirstRowNum;
                    int rLast = sheet.LastRowNum;

                    for (int i = rFirst+1; i < rLast+1; i++)
                    {
                        IRow ir = sheet.GetRow(i);
                        Student student = new Student
                        {
                            Id = ir.GetCell(0).ToString(),
                            Name = ir.GetCell(1).ToString(),
                            Sex = ir.GetCell(2).ToString(),
                            Chinese = ir.GetCell(4).ToString(),
                            Math = ir.GetCell(5).ToString(),
                            English = ir.GetCell(6).ToString(),
                            Physics = ir.GetCell(7).ToString(),
                            Chemistry = ir.GetCell(8).ToString(),
                            Biology = ir.GetCell(9).ToString(),
                            Politics = ir.GetCell(10).ToString(),
                            History = ir.GetCell(11).ToString(),
                            Geography = ir.GetCell(12).ToString(),
                            Computer = ir.GetCell(13).ToString()
                        };


                        Students.Add(student);
                        ir = null;
                    }
                    sheet = null;
                    book = null;
                }
            }
            catch (Exception e)
            {

                Console.WriteLine(e.ToString());
                Console.ReadKey();
            }
            return Students;
        }

        public void GenByGroup(GroupList rawList)
        {
            var classifyByGroup =
                from student in Students
                group student by new
                {
                    student.Chinese, student.Math, student.English, student.Physics, student.Chemistry, student.Biology, student.Politics, student.History, student.Geography, student.Computer
                } into stuGroup
                orderby stuGroup.Count() descending 
                select new
                {
                    count = stuGroup.Count(), stuGroup.Key.Chinese, stuGroup.Key.Math, stuGroup.Key.English, stuGroup.Key.Physics, stuGroup.Key.Chemistry, stuGroup.Key.Biology, stuGroup.Key.Politics, stuGroup.Key.History, stuGroup.Key.Geography, stuGroup.Key.Computer
                };

            foreach (var item in classifyByGroup)
            {
                Group group = new Group();
                group.Curriculum = new Curriculum();
                group.count = item.count;
                group.Details.Add(Coursename[0],item.Chinese);
                group.Details.Add(Coursename[1], item.Math);
                group.Details.Add(Coursename[2], item.English);
                group.Details.Add(Coursename[3], item.Physics);
                group.Details.Add(Coursename[4], item.Chemistry);
                group.Details.Add(Coursename[5], item.Biology);
                group.Details.Add(Coursename[6], item.Politics );
                group.Details.Add(Coursename[7], item.History);
                group.Details.Add(Coursename[8], item.Geography);
                group.Details.Add(Coursename[9], item.Computer );
                rawList.Add(group);
            }

        }

        /// <summary>
        /// 输出分班结果结果
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="outputLists"></param>
        public void OutputClassfiedClass(string filePath, List<GroupList> outputLists)
        {
            if (!string.IsNullOrEmpty(filePath) && null != outputLists && outputLists.Count > 0)
            {
                HSSFWorkbook book = new HSSFWorkbook();
                ISheet sheet = book.CreateSheet("分班情况");
                ISheet studentSheet = book.CreateSheet("学生明细");
                List<Dictionary<string,string>> studentList = new List<Dictionary<string, string>>();

                // 输出第一行标题
                IRow row0 = sheet.CreateRow(0);
                row0.CreateCell(0).SetCellValue("GroupID");
                for (int i = 0; i < Coursename.Count(); i++)
                {
                    row0.CreateCell(i + 1)
                        .SetCellValue(Coursename[i]);
                }

                row0.CreateCell(row0.LastCellNum).SetCellValue("人数");
                IRow stuRow = studentSheet.CreateRow(0);
                stuRow.CreateCell(0)
                   .SetCellValue("GroupID");
                stuRow.CreateCell(1)
                    .SetCellValue("学号");
                stuRow.CreateCell(2)
                    .SetCellValue("姓名");
                stuRow.CreateCell(3)
                    .SetCellValue("性别");

                for (int i = 0; i < Coursename.Length; i++)
                {
                    stuRow.CreateCell(i+4).SetCellValue(Coursename[i]);
                }
                int num = 14;
                foreach (KeyValuePair<string, double> scoreDetail in outputLists[0].StuList[0].scoreDetails)
                {
                    stuRow.CreateCell(num).SetCellValue(scoreDetail.Key);
                    num++;
                }

                
                // 输出每个group分组详细
                int rowNumber = 1;
                for (int k = 0; k < outputLists.Count; k++)
                {
                    foreach (Group @group in outputLists[k].List)
                    {
                        IRow row = sheet.CreateRow(rowNumber);
                        row.CreateCell(0).SetCellValue(k);

                        for (int i = 0; i < Coursename.Length; i++)
                        {
                            row.CreateCell(i+1).SetCellValue(group.ClassDetails[Coursename[i]]);
                        }

                        row.CreateCell(row.LastCellNum).SetCellValue(group.count);
                        rowNumber++;                       
                    }
                }
                // 输出每个groupList的学生名单
                rowNumber = 1;
                for (int i = 0; i < outputLists.Count; i++)
                {
                    foreach (Student student in outputLists[i].StuList)
                    {
                        IRow row = studentSheet.CreateRow(rowNumber);
                        row.CreateCell(0).SetCellValue(i);
                        row.CreateCell(1)
                                .SetCellValue(student.Id);
                        row.CreateCell(2)
                            .SetCellValue(student.Name);
                        row.CreateCell(3)
                            .SetCellValue(student.Sex);
                        row.CreateCell(4)
                                .SetCellValue(student.Chinese);
                        row.CreateCell(5)
                            .SetCellValue(student.Math);
                        row.CreateCell(6)
                            .SetCellValue(student.English);
                        row.CreateCell(7)
                                .SetCellValue(student.Physics);
                        row.CreateCell(8)
                            .SetCellValue(student.Chemistry);
                        row.CreateCell(9)
                            .SetCellValue(student.Biology);
                        row.CreateCell(10)
                                .SetCellValue(student.Politics);
                        row.CreateCell(11)
                            .SetCellValue(student.History);
                        row.CreateCell(12)
                            .SetCellValue(student.Geography);
                        row.CreateCell(13)
                            .SetCellValue(student.Computer);

                        int number = 14;
                        foreach (var scoreDetail in student.scoreDetails)
                        {
                            row.CreateCell(number).SetCellValue(scoreDetail.Value);
                            number++;
                        }
                        rowNumber++;

                    }
                }

                
                // 写入到客户端  
                using (MemoryStream ms = new MemoryStream())
                {
                    book.Write(ms);
                    using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    {
                        byte[] data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                    book = null;
                }
            }

        }

        /// <summary>
        /// 输出相对应的Excel课程表
        /// </summary>
        /// <param name="filePath">保存文件的路径</param>
        /// <param name="outputLists">数据源</param>
        public void OutputToExcel(string filePath, List<GroupList> outputLists)
        {
            if (!string.IsNullOrEmpty(filePath) && null != outputLists && outputLists.Count > 0)
            {
                HSSFWorkbook book = new HSSFWorkbook();
                int id = 0;
                foreach (GroupList list in outputLists)
                {
                    foreach (Group @group in list.List)
                    {
                        String sheetName = "";
                        ISheet sheet;
                        foreach (string s in group.Details.Values)
                            sheetName += s;

                        try
                        {
                            sheet = book.CreateSheet(sheetName+id);
                            id++;
                        }
                        catch (Exception)
                        {
                            sheetName += new Random().Next(10);
                            sheet = book.CreateSheet(sheetName);
                        }
                        
                        // 导出每个分组的课程表
                        IRow row1 = sheet.CreateRow(0);
                        for (int i = 0; i < 5; i++)
                        {
                            row1.CreateCell(i + 1)
                                .SetCellValue(DayName[i]);
                        }
                        IRow row;
                        for (int i = 0; i < CourseNumADay; i++)
                        {
                            row = sheet.CreateRow(i + 1);
                            for (int j = 0; j < 6; j++)
                            {
                                // 将忽略的课程直接写进class中
                                if (j > 0 && (group.Curriculum.table[j - 1][i].CourseName == "音乐"
                                    || group.Curriculum.table[j - 1][i].CourseName == "美术"
                                    || group.Curriculum.table[j - 1][i].CourseName == "体育"))
                                {
                                    group.Curriculum.table[j - 1][i].Class =
                                        group.Curriculum.table[j - 1][i].CourseName;
                                }

                                row.CreateCell(j)
                                    .SetCellValue(j == 0 ? (i+1).ToString() : (@group.Curriculum.table[j-1][i].Class
                                    +"\n("+@group.Curriculum.table[j-1][i].ClassroomNumber+"教室)"
                                    +"\n("+@group.Curriculum.table[j-1][i].TeacherId+"老师)"));
                                
                            }
                        }

                        IRow endRow = sheet.CreateRow(10);
                        endRow.CreateCell(0).SetCellValue(sheetName);
                        CellRangeAddress cellRangeAddress = new CellRangeAddress(10, 10, 0, 3);
                        sheet.AddMergedRegion(cellRangeAddress);

                        
                        // 将该分组对应的人员信息导入进来
                        List<Student> stu = new List<Student>();
                        foreach (Student student in Students)
                        {
                            if (student.Biology == group.Details["生物"]
                                && student.Chemistry == group.Details["化学"]
                                && student.Chinese == group.Details["语文"]
                                && student.Computer == group.Details["通技"]
                                && student.English == group.Details["英语"]
                                && student.Geography == group.Details["地理"]
                                && student.History == group.Details["历史"]
                                && student.Math == group.Details["数学"]
                                && student.Physics == group.Details["物理"]
                                && student.Politics == group.Details["政治"])
                            {
                                stu.Add(student);
                            }
                        }

                        row = sheet.CreateRow(11);
                        row.CreateCell(0)
                            .SetCellValue("学号");
                        row.CreateCell(1)
                            .SetCellValue("姓名");
                        row.CreateCell(2)
                            .SetCellValue("性别");


                        for (int i = 0; i < stu.Count; i++)
                        {
                            row = sheet.CreateRow(i + 12);
                            row.CreateCell(0)
                                .SetCellValue(stu[i].Id);
                            row.CreateCell(1)
                                .SetCellValue(stu[i].Name);
                            row.CreateCell(2)
                                .SetCellValue(stu[i].Sex);
                        }


                    }
                }

                // 写入到客户端  
                using (MemoryStream ms = new MemoryStream())
                {
                    book.Write(ms);
                    using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    {
                        byte[] data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                    book = null;
                }
            }

        }

   
        public void OutputToExcelMainCourse(string filePath, List<GroupList> outputLists)
        {
            if (!string.IsNullOrEmpty(filePath) && null != outputLists && outputLists.Count > 0)
            {
                HSSFWorkbook book = new HSSFWorkbook();
                int id = 0;
                foreach (GroupList list in outputLists)
                {
                    foreach (Group @group in list.List)
                    {
                        String sheetName = "";
                        ISheet sheet;
                        foreach (string s in group.Details.Values)
                            sheetName += s.Substring(2,1);

                        try
                        {
                            sheet = book.CreateSheet(sheetName + id);
                            id++;
                        }
                        catch (Exception)
                        {
                            sheetName += new Random().Next(10);
                            sheet = book.CreateSheet(sheetName);
                        }

                        // 导出每个分组的课程表
                        IRow row1 = sheet.CreateRow(0);
                        for (int i = 0; i < 5; i++)
                        {
                            row1.CreateCell(i + 1)
                                .SetCellValue(DayName[i]);
                        }
                        IRow row;
                        for (int i = 0; i < CourseNumADay; i++)
                        {
                            row = sheet.CreateRow(i + 1);
                            for (int j = 0; j < 6; j++)
                            {
                                if (j == 0)
                                {
                                    row.CreateCell(j)
                                        .SetCellValue((i + 1).ToString());
                                }
                                else if (@group.Curriculum.table[j - 1][i].Class != null)
                                {
                                    if (@group.Curriculum.table[j - 1][i].CourseName == "体育" 
                                        || @group.Curriculum.table[j - 1][i].CourseName == "音乐"
                                        || @group.Curriculum.table[j - 1][i].CourseName == "美术" )
                                    {
                                        row.CreateCell(j)
                                            .SetCellValue(@group.Curriculum.table[j - 1][i].CourseName);
                                    }
                                    else
                                    {
                                        row.CreateCell(j)
                                        .SetCellValue(@group.Curriculum.table[j - 1][i].Class
                                        + "\r\n(" + @group.Curriculum.table[j - 1][i].ClassroomNumber + "教室)"
                                        + "\r\n(" + @group.Curriculum.table[j - 1][i].TeacherId + "老师)");
                                    }
                                    
                                }
                                

                            }
                        }

                        IRow endRow = sheet.CreateRow(10);
                        endRow.CreateCell(0).SetCellValue(sheetName);
                        CellRangeAddress cellRangeAddress = new CellRangeAddress(10, 10, 0, 3);
                        sheet.AddMergedRegion(cellRangeAddress);

                    }
                }

                // 写入到客户端  
                using (MemoryStream ms = new MemoryStream())
                {
                    book.Write(ms);
                    using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    {
                        byte[] data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                    book = null;
                }
            }

        }

        
			
        public void OutputTeacherTable(string filePath, EnergyTable betterEnergyTable, string discipline)
        {
			// 记录老师的上课时间

            HSSFWorkbook book = new HSSFWorkbook();

            int teacherAmount = 0;
            string teacherName = null;
            for (int i = 0; i < Coursename.Count(); i++)
                if (Coursename[i] == discipline)
                    teacherAmount = AllTeacherList[i].Count;

            for (int m = 0; m < teacherAmount; m++)
            {
                teacherName = discipline + (char)(65+m);
                ISheet sheet = book.CreateSheet(teacherName);
                string[,] teacherTable = new string[5,9];
                foreach (GroupList list in betterEnergyTable.CompareList)
                    foreach (Group @group in list.List)
                        for (int i = 0; i < group.Curriculum.table.Count; i++)
                            for (int j = 0; j < group.Curriculum.table[i].Count; j++)
                                if (group.Curriculum.table[i][j].TeacherId == teacherName)
                                    if (teacherTable[i, j] != null
                                        && teacherTable[i, j].Contains(group.Curriculum.table[i][j].Class))
                                        ;
                                    else
                                    {

                                        // 班级和人数

                                        teacherTable[i, j] += group.Curriculum.table[i][j].Class;
                                        foreach (string[] strings in courseAmount)
                                        {
                                            if (strings[0] == group.Curriculum.table[i][j].Class)
                                            {
                                                teacherTable[i, j] += "\n(" + strings[1] + "人)" + group.Curriculum.table[i][j].ClassroomNumber+"教室";
                                                break;
                                            }
                                                
                                        }
                                    }
                                        

                // 导出每个分组的课程表
                IRow row1 = sheet.CreateRow(0);
                for (int i = 0; i < 5; i++)
                {
                    row1.CreateCell(i + 1)
                        .SetCellValue(DayName[i]);
                }
                IRow row;
                for (int i = 0; i < CourseNumADay; i++)
                {
                    row = sheet.CreateRow(i + 1);
                    for (int j = 0; j < 6; j++)
                    {
                        if (j == 0)
                        {
                            row.CreateCell(j)
                                .SetCellValue((i + 1).ToString() );
                        }
                        else
                        {
                            row.CreateCell(j)
                                .SetCellValue(teacherTable[j - 1,i]);
                        }

                    }
                }
            }

            // 写入到客户端  
            using (MemoryStream ms = new MemoryStream())
            {
                book.Write(ms);
                using (FileStream fs = new FileStream(filePath+discipline+".xls", FileMode.Create, FileAccess.Write))
                {
                    byte[] data = ms.ToArray();
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                }
                book = null;
            }
        }

        /// <summary>
        /// 存储老师的上课时间
        /// </summary>
        /// <param name="betterEnergyTable"></param>
		public void StoreTeacherTakeCoursePosition(EnergyTable betterEnergyTable)
		{
			teacherTakeCourseTime  = new Dictionary<string, List<int>>();
			foreach (var discipline in Coursename)
			{
				int teacherAmount = 0;
				string teacherName = null;

                // 获取该科目的老师数目
				for (int i = 0; i < Coursename.Count(); i++)
					if (Coursename[i] == discipline)
						teacherAmount = AllTeacherList[i].Count;

                //  获取该科目的每位老师的上课时间
				for (int m = 0; m < teacherAmount; m++) 
				{
					teacherName = discipline + (char)(65 + m);

					teacherTakeCourseTime.Add (teacherName, new List<int> ());

					List<int> coursePosition = new List<int> ();

                    //  便利每个类别的课程表获取老师的上课时间
					foreach (GroupList list in betterEnergyTable.CompareList)
						foreach (Group @group in list.List)
							for (int i = 0; i < group.Curriculum.table.Count; i++)
								for (int j = 0; j < group.Curriculum.table [i].Count; j++)
                                    if (group.Curriculum.table[i][j].TeacherId == teacherName)
                                    {
                                        if (coursePosition.Contains(i * 10 + j)) //  若该时间已经录入，则跳过
                                            ;
                                        else coursePosition.Add(i * 10 + j); // 将课程位置加入列表中
                                    }
									

					teacherTakeCourseTime [teacherName] = coursePosition;

				}
			}

		}

		private int CalculateTeacherTakeCourseEnergyValue(int day)
		{
			int sum = 0;
			foreach (var teacher in teacherTakeCourseTime)
			{
				int teacherSum = 0;
				HashSet<int> positionSet = new HashSet<int> ();
				List<int> positionList = new List<int> ();
				for (int i = 0; i < teacher.Value.Count; i++)
				{
					if (teacher.Value[i] / 10 == day) 
					{
						positionSet.Add (teacher.Value[i]);
						if (!positionList.Contains (teacher.Value[i]))
						{
								positionList.Add (teacher.Value[i]);
						}

					}
				}

				positionList.Sort ();
				for (int i = 0; i < positionList.Count-1; i++) 
				{
					teacherSum += (positionList [i + 1] - positionList [i]) * (positionList [i + 1] - positionList [i]);
				}
				sum += teacherSum;
			}
			return sum;
		}

		public void ExchangeSpecificPositionAllCourses(EnergyTable BetterEnergyTable, int day)
		{
			// 计算能量值
			double rawSum = CalculateTeacherTakeCourseEnergyValue (day);
			// 交换指定的那一天的课程
			Console.WriteLine ("交换前："+rawSum);
			EnergyTable exchangedEnergyTable;


			//遍历交换任意两门课程

            for (int j = 0; j < CourseNumADay; j++)
			{
                for (int k = j + 1; k < CourseNumADay; k++)
				{
					exchangedEnergyTable = new EnergyTable(BetterEnergyTable.CompareList);

					// 交换固定位置的所有课程

                    StreamWriter sw = new StreamWriter("交换.txt");

					foreach (var group in exchangedEnergyTable.CompareList) 
					{
						foreach (var smallGroup in group.List)
						{
                            // 判断交换的位置是否是不排课的位置
						    if (smallGroup.Curriculum.table[day][j].CourseName =="!" 
                                || smallGroup.Curriculum.table[day][k].CourseName == "!")
						    {
						        break;
						    }
							var tempCell = smallGroup.Curriculum.table [day] [j];
							smallGroup.Curriculum.table [day] [j] = smallGroup.Curriculum.table [day] [k];
							smallGroup.Curriculum.table [day] [k] = tempCell;

						    int p = smallGroup.Curriculum.table[day][j].PositionClass;
                            smallGroup.Curriculum.table[day][j].PositionClass = smallGroup.Curriculum.table[day][k].PositionClass;
                            smallGroup.Curriculum.table[day][k].PositionClass = p;
                            sw.WriteLine(day+j+smallGroup.Curriculum.table[day][j].TeacherId + "+" + day+k+smallGroup.Curriculum.table[day][k].TeacherId);
						}
					}

                    sw.Close();
                    
					StoreTeacherTakeCoursePosition (exchangedEnergyTable);

					if (rawSum > CalculateTeacherTakeCourseEnergyValue (day))
					{
						BetterEnergyTable.CompareList = exchangedEnergyTable.CompareList;
						rawSum = CalculateTeacherTakeCourseEnergyValue (day);
						Console.WriteLine(rawSum);

					}
						 

				}
			}
				
		}

		public void GenNewTeacherTakeCoursePosition(EnergyTable BetterEnergyTable,int day,int times)
		 {
			for (int i = 0; i < times; i++)
			{
				// 交换固定位置的所有课程
				Thread.Sleep(20);
				Random random = new Random((int)DateTime.Now.Ticks & 0x0000FFFF);

                int j = random.Next(CourseNumADay);
                int k = random.Next(CourseNumADay);
				foreach (var group in BetterEnergyTable.CompareList) 
				{
					foreach (var smallGroup in group.List)
					{
                        // 判断交换的位置是否是不排课的位置
                        if (smallGroup.Curriculum.table[day][j].CourseName == "!"
                            || smallGroup.Curriculum.table[day][k].CourseName == "!")
                        {
                            break;
                        }
                        var tempCell = smallGroup.Curriculum.table[day][j];
                        smallGroup.Curriculum.table[day][j] = smallGroup.Curriculum.table[day][k];
                        smallGroup.Curriculum.table[day][k] = tempCell;

                        int p = smallGroup.Curriculum.table[day][j].PositionClass;
                        smallGroup.Curriculum.table[day][j].PositionClass = smallGroup.Curriculum.table[day][k].PositionClass;
                        smallGroup.Curriculum.table[day][k].PositionClass = p;
                    }
				}
				
			}

		}

        
        public void OutPutCourseTableFile(string folderPath, List<GroupList> resultGroupList)
        {
            for (int i = 0; i < resultGroupList.Count; i++)
            {
                for (int j = 0; j < resultGroupList[i].List.Count; j++)
                {
                    // 输出分组的文件名
                    string fileName = "group." + i + "." + j + ".txt";
                    FileStream steam = new FileStream("./" + folderPath + "/" + fileName, FileMode.Create, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(steam);
                    var table = resultGroupList[i].List[j].Curriculum.table;
                    foreach (var cells in table)
                    {
                        foreach (var cell in cells)
                        {
                            sw.Write((cell.CourseName == "!"?cell.CourseName:cell.Class) +" ");

                        }
                        sw.WriteLine();
                    }

                    sw.Close();
                }
            }
        }
        // 输出课程教室时间对照表
        public void OutputCourseTimePairs(string filePath, List<GroupList> resultGroupLists)
        {
            Dictionary<string, HashSet<int>> pureClassCourseTime = new Dictionary<string, HashSet<int>>();
            Dictionary<string, HashSet<int>> mixedClassCourseTime = new Dictionary<string, HashSet<int>>();
            for (int k = 0; k < resultGroupLists.Count; k++)
            {
                GroupList list = resultGroupLists[k];
                for (int i = 0; i < list.List[0].Curriculum.table.Count; i++)
                {
                    List<CourseCell> cells = list.List[0].Curriculum.table[i];
                    for (int j = 0; j < cells.Count; j++)
                    {
                        CourseCell cell = cells[j];
                        HashSet<int> time = new HashSet<int>();

                        // 判断课程性质
                        // 若为纯班
                        // 半混班和纯班的处理方法一样
                        if ((cell.isSpecialCourse == 0 || cell.isSpecialCourse == 2) && cell.CourseName != "!")
                        {
                            if (cell.CourseName == "可调")
                            {
                                pureClassCourseTime.TryGetValue(cell.CourseName, out time);
                                if (time != null)
                                    time.Add(i * CourseNumADay + j);
                                else
                                    pureClassCourseTime.Add(cell.CourseName, new HashSet<int>() { (i * CourseNumADay + j) });

                                continue;
                            }
                            // 体音美咋整？
                            if (cell.CourseName == "体育" || cell.CourseName == "音乐" || cell.CourseName == "美术")
                            {
                                pureClassCourseTime.TryGetValue(cell.CourseName, out time);
                                cell.Class = cell.CourseName + k;

                            }

                            pureClassCourseTime.TryGetValue(cell.Class, out time);

                            if (time != null)
                                time.Add(i * CourseNumADay + j);
                            else
                                pureClassCourseTime.Add(cell.Class, new HashSet<int>() { (i * CourseNumADay + j) });
                        }
                        // 混合班只需要添加科目名称，不需要添加课程名称
                        else if (cell.isSpecialCourse == 1)
                        {
                            if (mixedClassCourseTime.TryGetValue(cell.Class.Substring(0, 2), out time))
                                time.Add(i * CourseNumADay + j);
                            else
                                mixedClassCourseTime.Add(cell.Class.Substring(0, 2), new HashSet<int>() { (i * CourseNumADay + j) });
                        }

                    }
                }
            }

            //  将数据输出至文本文件中
            FileStream fileStream = new FileStream(filePath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fileStream);

            // 输出纯班数据
            foreach (KeyValuePair<string, HashSet<int>> pair in pureClassCourseTime)
            {
                foreach (int i in pair.Value)
                {
                    sw.WriteLine(pair.Key + " " + i);
                }
            }
            // 输出混合班数据
            sw.WriteLine("混合班");
            foreach (KeyValuePair<string, HashSet<int>> pair in mixedClassCourseTime)
            {
                foreach (int i in pair.Value)
                {
                    sw.WriteLine(pair.Key + " " + i);
                }
            }

            sw.Close();
        }
    }
}
